using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using Clandestine.Engines.Field;

namespace Shlick
{
	using Object = Clandestine.Engines.Field.Object;

	public class ObjectDeleteCommand : ICommand
	{
		public string Name { get { return "Delete Object"; } }
		private Object obj;
		private Level level;
		
		// Save the xml of the object here on delete so we can re-create it!
		// It'll only be small, and it's actually better than keeping it in vram.. small load times (Or you'd hope they were small.)
		private byte[] data;
		
		public ObjectDeleteCommand(Object obj)
		{
			this.obj = obj;
			this.level = this.obj.Level; // so we know which level to re-add to
		}
		
		public static ICommand DeleteMultiple(List<Object> objects)
		{
			List<ICommand> cmds = new List<ICommand>();
			foreach (Object o in objects)
				cmds.Add(new ObjectDeleteCommand(o));
			return new CommandCollection("Delete Object(s)", cmds);
		}
		
		public void Do ()
		{
			// Save the object to byte[] as xml
			MemoryStream stream = new MemoryStream();
			XmlWriter xml = XmlWriter.Create(stream);
			this.obj.Save(xml);
			xml.Close();
			stream.Flush();
			data = stream.GetBuffer();
			stream.Close();
			
			// Delete object
			this.level.RemoveObject(this.obj);
			this.obj = null; // hopefully allow GC
			
		}

		public void Undo ()
		{
			// Load the object from byte[] as xml
			MemoryStream stream = new MemoryStream(data);
			XmlReader xml = XmlReader.Create(stream);
			this.obj = this.level.AddObject(xml);
			xml.Close();
			stream.Close();
			data = null;
		}
	}
}

